#ifndef NETWORK_H
#define NETWORK_H

#include <QObject>
#include <QList>
#include <QByteArray>
#include <QTextCodec>
#include <QHostAddress>

#include <QTcpSocket>
#include <QTcpServer>
#include <QUdpSocket>


class network : public QObject
{
    Q_OBJECT
public:
    explicit network(QObject *parent = nullptr);
    // 数据缓存区
    QByteArray TCPServer_dataBuf;
    QByteArray TCPClient_dataBuf;
    QByteArray UDP_dataBuf;
    // 发送/接收字节数
    int TCPServer_txByte = 0;
    int TCPServer_rxByte = 0;
    int TCPClient_txByte = 0;
    int TCPClient_rxByte = 0;
    int UDP_txByte = 0;
    int UDP_rxByte = 0;

    bool TCPServer_open(QString ownIp, unsigned short ownPort);
    void TCPServer_close();
    void TCPServer_sendData(QByteArray sendData);

    bool TCPClient_open(QString remoteIp, unsigned short remotePort);
    void TCPClient_close();
    void TCPClient_sendData(QByteArray sendData);

    bool UDP_open(QString ownIp, unsigned short ownPort, QString remoteIp, unsigned short remotePort);
    void UDP_close();
    void UDP_sendData(QByteArray sendData);
private:
    QTextCodec *tc; // 编码
    QTcpServer *tcpServer; // tcp服务端
    QList<QTcpSocket*> clientList; // 保存连接的客户端
    QTcpSocket *tcpClient; // tcp客户端
    QUdpSocket *udpSocket; // udp
    QHostAddress UDP_remoteIp;
    unsigned short UDP_remotePort;
signals:
    void tcpServer_readSuccess(int recByte);
    void tcpServer_sendSuccess(int sendByte);

    void tcpClient_readSuccess(int recByte);
    void tcpClient_sendSuccess(int sendByte);

    void udp_readSuccess(int recByte);
    void udp_sendSuccess(int sendByte);
private slots:
    void TCPServer_readData();
    void TCPServer_newConnect();
    void TCPServer_disconnect();

    void TCPClient_readData();
    void TCPClient_newConnect();
    void TCPClient_disconnect();

    void UDP_readData();
};

#endif // NETWORK_H
